from flask import Blueprint,request,make_response,jsonify,redirect
from flask_restful import Resource,Api
from utils.captcha.captcha import captcha
from utils.Myredis import r
import json
from utils.comm import send_message
import requests
import random
from application.models.users.user import *
from application.models.users.user import db
import time
from utils.Myjwt import myjwt
login_blue=Blueprint("login",__name__)
api=Api(login_blue)
# 获取图片验证码
@login_blue.route("/getimg")
def getimg():
    # 调用captcha生成图片验证码
    name,text,img=captcha.generate_captcha()
    # 存入redis字符串 key:uuid value:text
    uuid=request.args.get("uuid")
    # 存入redis
    r.str_setex(uuid,text,300)
    res=make_response(img)
    # 以流的方式生成图片验证码
    res.headers["Content-Type"]="image/jpg"
    return res
# 发送短信验证码
@login_blue.route("/sms",methods=["POST"])
def sms():
    # 获取参数
    data=json.loads(request.data)
    mobile=data["mobile"]
    uuid=data["uuid"]
    imagecode=data["imagecode"]
    if not all([mobile,uuid,imagecode]):
        return jsonify({"code":401,"msg":"参数不完整"})
    # 验证图片验证码
    code=r.get_str(uuid)
    # 通过uuid从redis取出来和传递过来的参数进行对比，全部转为小写
    if code:
        if imagecode.lower()==code.lower().decode():
            # 验证一分钟之内只能发送一次
            mcode=r.get_str(mobile)
            if mcode:
                return jsonify({"code":403,"msg":"一分钟只能发送一次"})
            # 生成随机数
            scode=str(random.randint(1000,9999))
            print(scode)
            # 调用短信平台
            flag=send_message(mobile,scode)
            print('.......asddddddddd',flag)
            # if flag==True:
            # 存入redis
            r.add_str(mobile,scode)
            # 清除redis中的图片验证码
            r.del_key(uuid)
            # 返回结果
            return jsonify({"code": 200, "msg": "发送成功"})
            # else:
            #     return jsonify({"code": 403, "msg": "发送验证码失败"})
        else:
            return jsonify({"code":402,"msg":"图片验证码不正确"})
        # 失败返回错误信息
    else:
        return jsonify({"code":403,"msg":"验证码不存在"})

# 登陆
@login_blue.route("/login",methods=["POST"])
def login():
    # 获取参数
    data=json.loads(request.data)
    if data:
        mcode=data["mcode"]
        mobile=data["mobile"]
        # 根据手机号去redis获取验证码
        code=r.get_str(mobile)
        print("rrrrrrr",code)
        if code:
            # 验证码是否相同
            if int(code)==int(mcode):
                # 如果相同查询数据库user表，存在返回信息
                u=User.query.filter(User.mobile==mobile).first()
                if u:
                    # 删除redis中的验证码
                    r.del_key(mobile)
                # 不存在写入用户表
                else:
                    u=User(mobile=mobile,nikename=mobile)
                    db.session.add(u)
                    db.session.commit()
                token = myjwt.jwt_encode({"data": {"userid": u.id ,"mobile": u.mobile, "exptime": int(time.time())}})
                return jsonify({"code": 200, "msg": "登陆成功","token":token,"userid":u.id})
            else:
                return jsonify({"code":201,"msg":"验证码错误"})
        else:
            return jsonify({"code":200,"msg":"验证码过期"})


# 装饰器
# 权限认证
# def islogin(func):
#     @functools.wraps(func)
#     def wrapper():
#         func()
#         # 权限验证判断,如果有问题返回
#         return func()
#     return wrapper
# def islogin(type):
#     def pemistion(func):
#         @functools.wraps(func)
#         def wrapper():
#             func()
#             if type == 1:
#                 return redirect("http://www.baidu.com")
#             else:
#                 return redirect("http://www.jd.com")
#         return wrapper
#     return pemistion

# 测试
@login_blue.route("/cart")
# @islogin(2)
def cart():
    print("执行cart")
    return jsonify({"code": 200, "msg": 'msg'})
@login_blue.route('/tiao')
def tiao():
    client_id = "3674019597"
    redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
    # 微博平台地址
    url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s" % (
    client_id, redirect_uri)
    return jsonify({'code':200,'url':url})


# 设置回调地址
@login_blue.route('/user/weiboCallback/')
def hui():
    code = request.args.get('code')
    data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
            "grant_type": "authorization_code",
            'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
    res = requests.post('https://api.weibo.com/oauth2/access_token',data=data)
    #获取token和uid
    message = json.loads(res.text)
    print('666',message)
    token = message['access_token']
    uid = message['uid']
    #判断表中是否有数据
    u = db.session.execute("select user.id,user.mobile from sf_login inner join user on sf_login.userid=user.id where sf_login.uid='%s'"%(str(uid)))
    # sql = "select user.id,user.mobile  from sf_login inner join user on sf_login.userid=user.id where sf_login.uid='%s'"%(str(uid))
    # user = db.fetchone(sql)
    user = list(u)
    if user:
        for i in user:
            print('i',i)
            token = myjwt.jwt_encode(
                data ={'data':{'uid':i[0],'mobile':i[1],'exp':int(time.time())}}
            )
            return redirect("http://localhost:8080/#/login?token=" + token + "&uid=" + str(i[1]))
    else:
        print(token)
        return redirect("http://localhost:8080/#/bang?token=" + str(token) + "&uid=" + str(uid))

@login_blue.route('/bang',methods=['POST'])
def bang():
    data = json.loads(request.data)
    #判断手机号是否存在用户表
    user = User.query.filter_by(mobile=data['mobile']).first()
    if user:
        #加入三方登录表
        sf = SfLogin(userid=user.id,webfrom='weibe',uid=data['uid'],token=data['token'])
        db.session.add(sf)
        db.session.commit()
        data = {"data": {"userid": user.id, "mobile": user.mobile, "exptime": int(time.time())}}
        token = myjwt.jwt_encode(data)
        return jsonify({"code": 200, "msg": "登录成功", "token": token, "userid": user.id, "mobile": user.mobile})
    else:
        # 加入用户表
        admin = User(mobile=data["mobile"],password=data['password'],nikename=158399)
        userid = db.session.add(admin)
        # 加入三方登录表
        sf = SfLogin(userid=userid, webfrom="weibo", uid=data["uid"], token=data["token"])
        db.session.add(sf)
        db.session.commit()
        # 生成token
        data = {"data": {"userid": userid, "mobile": admin.mobile, "exptime": int(time.time())}}
        token = myjwt.jwt_encode(data)
        return jsonify({"code": 200, "msg": "登录成功", "token": token, "userid": userid, "mobile": admin.mobile})



from utils.comm import get_ali_object
@login_blue.route('/zhan')
def get():
    alipay = get_ali_object()
    query_params = alipay.direct_pay(
        subject='test',  # 商品简单描述
        out_trade_no=str('1234567'),  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(100.00),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({'code':200,'url':pay_url})

@login_blue.route('/setVip',methods=['POST'])
def setVip():
    data = json.loads(request.data)
    userid = data['userid']
    year = data['year']
    money = 200
    order_no = str(int(time.time()))+str(userid)+str(random.randint(100,999))
    tmoney = int(money) *int(year)
    vip = VipRecord(userid=userid,year=year,money=tmoney,active_money=tmoney,status=1,order_no=order_no)
    db.session.add(vip)
    db.session.commit()
    alipay = get_ali_object()
    query_params = alipay.direct_pay(
        subject=str(userid),  # 商品简单描述
        out_trade_no=order_no,  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(tmoney),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({'code': 200, 'url': pay_url})
import datetime
@login_blue.route('/user/callback/')
def call():
    order_no = request.args.get('out_trade_no')
    print('lllll',order_no)
    res = VipRecord.query.filter_by(order_no=order_no).first()
    print(res)
    uid = int(res.userid)
    year=res.year
    if int(year)==1:
        year=365
    elif int(year)==2:
        year = 365*2
    elif int(year)==3:
        year = 365*3
    # try:
    stime = datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%M:%S")
    etime = datetime.datetime.now() +datetime.timedelta(days=year)
    etime = datetime.datetime.strftime(etime,"%Y-%m-%d %H:%M:%S")
    vip = Vip(userid=uid,s_time=stime,e_time=etime)
    db.session.add(vip)

    order=VipRecord.query.filter_by(order_no=order_no).first()
    order.status = 2
    user = User.query.filter_by(id=uid).first()
    user.level = 2
    # User.query.filter_by(userid=uid).update(level=2)
    db.session.commit()
    # except:
    #     db.session.rollback()
    return redirect("http://localhost:8080/#/vip")



@login_blue.route('/liangji')
def k():
    list = [{"id": 1, 'name': '分类1', 'pid': 0}, {"id": 2, 'name': '分类2', 'pid': 0}, {"id": 3, 'name': '分类11', 'pid': 1},
            {"id": 4, 'name': '分类12', 'pid': 1}, {"id": 5, 'name': '分类21', 'pid': 2}]
    rlist = []
    ids = []
    # 把父类放入列表中
    for i in list:
        if i['pid'] ==0:
            #去重
            if i['id'] not in ids:
                rlist.append({'id':i['id'],'name':i['name'],'son':[]})
                ids.append(i['id'])
    # 遍历父类，遍历list,对比，如果当前list中的pid和父类中的id相同
    for index,j in enumerate(rlist):
        for i in list:
            if j['id'] == i['pid']:
                rlist[index]['son'].append(i)

    print(rlist)
    return jsonify({'k':rlist})
@login_blue.route('/wuxian')
def wuxian():
    list = [{"id": 1, 'name': '分类1', 'pid': 0}, {"id": 2, 'name': '分类2', 'pid': 0}, {"id": 3, 'name': '分类11', 'pid': 1},
            {"id": 4, 'name': '分类12', 'pid': 1}, {"id": 5, 'name': '分类21', 'pid': 2},
            {"id": 6, 'name': '分类111', 'pid': 3}, {"id": 7, 'name': '分类1111', 'pid': 6},
            {"id": 8, 'name': '分类1111', 'pid': 7}]
    rdict = {}
    reslist = []
    # 读取列表中的每一个放到字典中
    for i in list:
        k = i['id']
        rdict[k] = i
    #判断子类属于那个父类，放到父类的son
    for j in list:
        pid = j['pid']
        if pid ==0:
            reslist.append(j)
        else:
            if 'son' not in rdict[pid]:

                rdict[pid]['son'] =[]
            rdict[pid]['son'].append(j)
    return jsonify({'k': rdict})
@login_blue.route('/liang')
def liang():
    list = [{"id": 1, 'name': '分类1', 'pid': 0}, {"id": 2, 'name': '分类2', 'pid': 0}, {"id": 3, 'name': '分类11', 'pid': 1},
            {"id": 4, 'name': '分类12', 'pid': 1}, {"id": 5, 'name': '分类21', 'pid': 2},
            {"id": 6, 'name': '分类111', 'pid': 3}, {"id": 7, 'name': '分类1111', 'pid': 6},
            {"id": 8, 'name': '分类1111', 'pid': 7}]
    rdict = {}
    reslist =[]
    for i in list:
        k = i['id']
        rdict[k] = i
    for j in list:
        pid = j['pid']
        if pid ==0:
            reslist.append(j)
        else:
            if 'son' not in rdict[pid]:
                rdict[pid]['son'] = []
            rdict[pid]['son'].append(j)
    return jsonify({'5':reslist})





